package netty.test22TcpSelfProto;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;

public class MySPClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count=0;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol msg) throws Exception {
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("客户端接收到的消息如下 len="+len);
        System.out.println("长度 len="+len);
        System.out.println("内容 content="+new String(content, CharsetUtil.UTF_8));
        System.out.println("客户端接收的消息次数 ="+(++count));
        System.out.println("=========================");


    }

    //重写channelActive发送数据

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("11111111111MyClientHandler执行了");
        //使用客户端发送10次数据
        for(int i=0;i<10;i++){
            String msg= "今天是初："+i;
            byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setLen(bytes.length);
            messageProtocol.setContent(bytes);
            ctx.writeAndFlush(messageProtocol);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
